<?php
class UsersController extends AppController {

	var $name = 'Users';
	var $helpers = array('Html', 'Form' );

	function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function view($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid User.');
			$this->redirect(array('action'=>'index'), null, true);
		}
		$this->set('user', $this->User->read(null, $id));
	}

	function add() {
		if(!empty($this->data)) {
			$this->cleanUpFields();
			$this->User->create();
			if($this->User->save($this->data)) {
				$this->Session->setFlash('The User has been saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The User could not be saved. Please, try again.');
			}
		}
		$groups = $this->User->Group->generateList();
		$this->set(compact('groups'));
	}

	function edit($id = null) {
		if(!$id && empty($this->data)) {
			$this->Session->setFlash('Invalid User');
			$this->redirect(array('action'=>'index'), null, true);
		}
		if(!empty($this->data)) {
			$this->cleanUpFields();
			if($this->User->save($this->data)) {
				$this->Session->setFlash('The User saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The User could not be saved. Please, try again.');
			}
		}
		if(empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->generateList();
		$this->set(compact('groups'));
	}

	function delete($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for User');
			$this->redirect(array('action'=>'index'), null, true);
		}
		if($this->User->del($id)) {
			$this->Session->setFlash('User #'.$id.' deleted');
			$this->redirect(array('action'=>'index'), null, true);
		}
	}


	function admin_index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function admin_view($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid User.');
			$this->redirect(array('action'=>'index'), null, true);
		}
		$this->set('user', $this->User->read(null, $id));
	}

	function admin_add() {
		if(!empty($this->data)) {
			$this->cleanUpFields();
			$this->data['User']['passwd'] = md5($this->data['User']['passwd']);
			$this->User->create();
			if($this->User->save($this->data)) {
				$this->Session->setFlash('The User has been saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The User could not be saved. Please, try again.');
			}
		}
		$groups = $this->User->Group->generateList();
		$this->set(compact('groups'));
	}

	function admin_edit($id = null) {
		if(!$id && empty($this->data)) {
			$this->Session->setFlash('Invalid User');
			$this->redirect(array('action'=>'index'), null, true);
		}
		if(!empty($this->data)) {
			$this->cleanUpFields();
			if($this->User->save($this->data)) {
				$this->Session->setFlash('The User saved');
				$this->redirect(array('action'=>'index'), null, true);
			} else {
				$this->Session->setFlash('The User could not be saved. Please, try again.');
			}
		}
		if(empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
		$groups = $this->User->Group->generateList();
		$this->set(compact('groups'));
	}

	function admin_delete($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for User');
			$this->redirect(array('action'=>'index'), null, true);
		}
		if($this->User->del($id)) {
			$this->Session->setFlash('User #'.$id.' deleted');
			$this->redirect(array('action'=>'index'), null, true);
		}
	}
	
	/**
	 * This is the function that controls login logic to othAuth
	 * @access public
	 */
	
	function login()
	{
		if( isset ( $this->data ) )
		{
			if ($this->Conf->get('general.enable_captcha'))
			{
				if (!$this->Session->read('captcha') == $this->data['User']['captcha_check'] )
				{
					return false;
				}
			}
			$auth_num = $this->othAuth->login($this->data['User']);
			$this->set('auth_msg', $this->othAuth->getMsg($auth_num));
		}
	}
	
	function logout()
	{
		$this->othAuth->logout();
		$this->Session->setFlash('You are now logged out');
		$this->redirect('/');
	}
	
	function noaccess()
	{
		$this->Session->setFlash('You do not have permssion to access this page.');
		$this->redirect('/users/login');
	}
	
	function openidlogin() {
    if (!empty($this->data)) {
        if ($this->User->create($this->data) && $this->User->validates()) {
            $this->Openid->authenticate($this->data['User']['openid'], 'http://'.$_SERVER['SERVER_NAME'].'/users/openidlogin', 'http://'.$_SERVER['SERVER_NAME'], array( array('sreg','required','nickname,email,country'), array('sreg','optional','dob') ) );
        }
    } else {
        if (count($_GET) > 1) {
            $response = $this->Openid->getResponse();

            if ($response->status == Auth_OpenID_SUCCESS) {
            	
				/**
				* First we need to check if the user already exists in our system
				* if they don't we then go on to create a user record
				*/
                if ($this->User->findByUsername($response->signed_args['openid.sreg.nickname']) ) {
					$this->Session->setFlash('User Authenticated Success');
					$this->Session->write('username', $response->signed_args['openid.sreg.nickname']);
					$this->redirect('/');
				} else {
					// Required Fields
					$this->User->data['username'] = $response->signed_args['openid.sreg.nickname'];
					$this->User->data['email'] = $response->signed_args['openid.sreg.email'];
					$this->User->data['openid'] = $response->identity_url;
								
					// Optional Fields
					if ( $response->signed_args['openid.sreg.dob'] ) {
						$this->User->data['dob'] = $response->signed_args['openid.sreg.dob'];
					}
									
					if ( $response->signed_args['openid.sreg.country'] ) {
						$this->User->data['country'] = $response->signed_args['openid.sreg.country'];
					}
									
					//if ( $this->User->save($this->User->data) )
					//{
						$this->Session->setFlash('User Authenticated Success.  Local User Record Created');
					//}
					}
				}
			}
		}
	}  // End OpenID Login

}
?>